<template>
  <div class="supplier-home">
    <!-- 不自定义装修 -->
    <div class="default-sup" v-if="supplier_info.is_diy==0">
      <div class="supplier">
        <section class="supplier-head-top">
          <section class="shop-logo j-shopLogo">
            <img v-if="supplier_info.logo" :src="supplier_info.logo" alt="" mode="scaleToFill">
            <img v-else src="https://img.wifenxiao.com/h5-wfx/images/default_shop_icon.png" alt="" mode="scaleToFill">
          </section>
          <section class="shop-title" :style="{'color': supplier_info.title_color?supplier_info.title_color:' #fff;'}">{{supplier_info.name}}</section>
          <section class="btn-member">
            <a @click="Jump('member')">会员中心</a>
          </section>
        </section>
        <section class="supplier-headerbot-ri">
          <ul class="clearfix">
            <li class="active">
              <!-- <span>{{resDetail.total_item}}</span> -->
              <a @click="Jump('item-list',{'supplier':resDetail.id})">全部商品</a>
              <i></i>
            </li>
            <li>
              <!-- <span>{{resDetail.new_item}}</span> -->
              <a @click="Jump('item-list',{'supplier':resDetail.id,'new':1})">上新商品</a>
              <i></i>
            </li>
            <!-- <li>
              <span><img src="~@/assets/images/hui1.png" width="18" height="16"></span>
              <a @click="Jump('user-member')">会员中心</a>
            </li> -->
          </ul>
        </section>
      </div>
      <div class="duodian-mlist-nav" :class="isSupplierStyle?'default':'fixed'">
        <!--排序搜索-->
        <sort-search @item="sortSearchFn" :typeList="typeList" :listStyle="listStyle"></sort-search>
      </div>
      <!-- 商品数据 -->
      <div class="newlist">
        <item-wrapper :itemList="itemList" :listStyle="listStyle" :vanList="vanList" :otherInfo="otherInfo" :isShowNoData="isShowNoData" @scrollReachBottom="getData"></item-wrapper>
      </div>
    </div>
    <!-- 自定义装修数据 -->
    <div class="diy-sup diyWrap" v-else :style="{'background-color':backgroundColor}">
      <van-list v-model="loading"
                  :finished="finished"
                  :error.sync="error"
                  error-text="请求失败，点击重新加载"
                  finished-text=""
                  @load="onLoad">
        <diy-tpl :tplData="tplData" :hasMargin="hasMargin" :supplierId="id"></diy-tpl>
      </van-list>
    </div>
    <!-- 授权弹出框 -->
    <small-login ref="smalllogin"></small-login>
    <!-- 微呗定制 展示供应商手机号 -->
    <template v-if="resDetail.is_weibei_dz">
      <div class="icon-tel" @click="is_show_supplier_tel = true"></div>
      <van-dialog
        class="common-confirm"
        v-model="is_show_supplier_tel"
        title="供应商联系电话"
        :show-confirm-button="true"
        :show-cancel-button="true"
        confirm-button-text="拨打电话"
        confirm-button-color="black"
        cancel-button-text="关闭"
        @confirm="callPhone(supplier_info.mobile)"
      >
        <div class="supplier-tel">
          <p class=tel>{{ supplier_info.mobile }}<span class="copy" @click="copySupplierTel(supplier_info.mobile,$event)">复制</span></p>
        </div>
      </van-dialog>
    </template>
    <!-- 微呗定制 展示供应商手机号 -->
  </div>
</template>

<script>
import diyTpl from '../index/shopTpl/index'
import { getSupplier, supplierDiyHtml, getSupplierLists } from '@/api/shop/index'
import { mpShare, openPage } from '@/utils/utils'
import sortSearch from '../../item/itemList/listWrapper/sortSearch'
import itemWrapper from '../../item/itemList/listWrapper/itemWrapper'
import SmallLogin from '@/components/SmallLogin/smallLogin.vue'
import small from '@/smallapp/small'
// import { wxSceneExchange } from '@/api/small/login'

import Vue from 'vue'

export default Vue.extend({
  components: {
    diyTpl,
    sortSearch,
    itemWrapper,
    SmallLogin
  },
  data() {
    return {
      height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,
      id: '',
      listStyle: false,
      resDetail: {},
      supplier_info: {},
      itemList: [],
      isShowNoData: false,
      typeList: [
        { label: '默认', active: true, type: 0, prop: 'default', sort: 'none' },
        { label: '价格', active: false, type: 1, prop: 'price', sort: '' },
        { label: '销量', active: false, type: 2, prop: 'sales', sort: '' },
        { label: '新品', active: false, type: 3, prop: 'new', sort: '' },
        // { label: '', active: false, type: 5, prop: 'listStyle', sort: 'none' }
      ],
      vanList: {
        loading: false,
        error: false,
        finished: false
      },
      // 装修数据
      backgroundColor: '',
      hasMargin: 0,
      tplData: [],
      loading: false,
      finished: false,
      error: false,
      firstLoading: true,
      p: 1,
      order: '',
      isSupplierStyle: true, // 排序导航为供应商首页样式
      otherInfo: {},
      // 微呗定制 显示供应商手机号
      is_show_supplier_tel: false
    }
  },
  computed: {

  },
  watch: {
    listStyle(val) {
      if (!val) {
        this.isSupplierStyle = true
      }
    }
  },
  beforeCreate() {
    // 页面title
      wx.setNavigationBarTitle({
        title: ''
      })
  },
  created() {
    // TODO 小程序商品列表去掉瀑布流
      this.listStyle = true
  },
  methods: {
    // 滚动事件
    handleScroll() {
      if (this.listStyle) {
          const scrollY = Math.ceil((document.documentElement.scrollTop || document.body.scrollTop))
          const supplierTop = document.querySelector('.default-sup .supplier')
          supplierTop.$$getBoundingClientRect().then((res) => {
            const supplierHeaderH = res.height
            if (scrollY >= supplierHeaderH) {
              this.isSupplierStyle = false
            } else {
              this.isSupplierStyle = true
            }
          })
      } else {
        return false
      }
    },
    Jump(url, data) {
      this.$JumpName(this, url, data)
    },
    sortSearchFn(data) {
      if (data.prop == 'listStyle') {
        this.listStyle = !this.listStyle
        // // console.log(9999)
        return false
      }
      if (data.prop == 'price') {
        this.order = data.sort == 'ascending' ? 'priceUp' : 'priceDown'
      } else if (data.prop == 'sales') {
        this.order = data.sort == 'ascending' ? 'salesUp' : 'salesDown'
      } else if (data.prop == 'new') {
        this.order = data.sort == 'ascending' ? 'newUp' : 'newDown'
      } else {
        this.order = 'default'
      }
      this.p = 1
      this.itemList = []
      this.getItemListPost()
    },
    /**
       * 滑到底部加载
       */
    getData() {
      this.p++
      this.getItemListPost()
    },

    // 加载更多商品列表
    getItemListPost() {
      const data = {
        id: this.id,
        p: this.p,
        order: this.order
      }
      getSupplierLists(data).then((res) => {
        this.vanList.loading = false
        const resData = res.data.lists
        if (resData.length <= 0) {
          if (this.$refs.waterfalls) {
            this.$refs.waterfalls.waterfallOver()
          }
          this.vanList.finished = true
        }
        resData.forEach((item) => {
          if (item.is_compress == 1) {
            item.src = `${item.pic_url}w640`
          } else {
            item.src = item.pic_url
          }
        })
        this.itemList = this.itemList.concat(resData)
      })
    },

    getSupplierFun() {
      this.vanList.finished = false
      this.vanList.loading = false
      this.vanList.error = false
      this.$loadingWrap.show()
      getSupplier({ id: this.id }).then((res) => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          const data = res.data
          // 分享数据处理
          this.handleShare(res.data)
          this.resDetail = data
          this.supplier_info = data.supplier_info
          if (data.hide_home_button == 1) {
            // 隐藏左上角home按钮
            wx.hideHomeButton({
              success: function() {
                // console.log('hideHomeButton-success')
              },
              fail: function() {
                // console.log('hideHomeButton-fail')
              },
              complete: function() {
                // console.log('hideHomeButton-complete')
              }
            })
          }
          // 页面title
            wx.setNavigationBarTitle({
              title: this.supplier_info.name
            })
          if (this.supplier_info.is_diy == 1) {
            this.id = data.supplier_id
            // 获取装修数据
            this.getSupplierDiyHtml()
          }
          this.otherInfo.is_display_original_price = data.is_display_original_price
          this.otherInfo.point_name = data.point_name

          // 商品列表处理
          const listData = data.lists
          if (listData.length == 0) {
            if (this.$refs.waterfalls) {
              this.$refs.waterfalls.waterfallOver()
            }
            this.vanList.finished = true
            this.isShowNoData = true
          } else {
            this.isShowNoData = false
          }
          listData.forEach((item) => {
            if (item.is_compress == 1) {
              item.src = `${item.pic_url}w640`
            } else {
              item.src = item.pic_url
            }
          })
          this.itemList = listData
        }
      }).catch((_) => {
        this.$loadingWrap.close()
      })
    },

    // 首页装修组件数据
    getSupplierDiyHtml() {
      supplierDiyHtml({ id: this.id }).then((res) => {
        if (res.status == 1) {
          const data = res.data
          this.p++
          // TODO 如果后台返回链接则跳转
          // console.log(data, typeof data, '供应商店铺数据')
          if (typeof data === 'string') {
            openPage(data)
          }
          this.backgroundColor = data.backgroundColor
          this.hasMargin = data.hasMargin
          this.tplData = data._diyHtml
          this.firstLoading = false
          if (this.tplData.length < 10) {
            this.finished = true
          }
          // TODO小程序如果第一页加载没有满屏 则继续加载
            if (!this.finished) {
              this.$nextTick(() => {
                document.querySelector('.diyWrap').$$getBoundingClientRect().then((res) => {
                  if (res.height * 1 < this.height * 1) {
                    this.onLoad()
                  }
                })
              })
            }
        }
      })
    },
    // 首页装修组件加载更多
    onLoad() {
      if (this.firstLoading) {
        this.loading = false
        return
      }
      const data = {
        p: this.p,
        id: this.id
      }
      supplierDiyHtml(data).then((res) => {
        if (res.status == 1) {
          this.loading = false
          const data = res.data
          this.tplData = this.tplData.concat(data._diyHtml)
          this.p++
          if (data._diyHtml.length < 10) {
            this.finished = true
          }
        }
      }).catch(() => {
        this.error = true
      })
    },

    handleShare(data) {
        // TODO 小程序分享
        this.shareInfo = {
          title: data.jsapi_title || '',
          imgUrl: data.jsapi_img || '',
          shareParam: data.jsapi_url ? data.jsapi_url.split('?')[1] : `sid=${small.globalData.shopId}&id=${data.id}&pid=${small.wxCache('global_login_info') ? small.wxCache('global_login_info').uid : '0'}`
        }
        // console.log("supplier-shareInfo", this.shareInfo)
        mpShare(true, true, '/goods/pages/supplier/index', this.shareInfo)
    },
    copySupplierTel(content, e) {
      wx.setClipboardData({
        data: content,
        success (res) {
          wx.showToast({
            title: '复制成功'
          })
        }
      })
    },
    callPhone(tel) {
      wx.makePhoneCall({
        phoneNumber: tel,
        success(){},
        fail(){}
      })
    }
  },
  mounted() {
    // 小程序触底加载更多
    window.addEventListener('reachbottom', () => {
      // 非自定义装修
      if (this.supplier_info.is_diy == 1) {
        // 自定义装修
        this.onLoad()
      } else {
        this.getData()
      }
    })
      window.addEventListener('wxload', (query) => {
        // console.log(query, '分享参数')
        small.HandleShareParams()
        this.id = this.$route.query.id ? this.$route.query.id : query.id
        small.wxCache('supidBar', this.id)
        this.getSupplierFun()
      })

      window.addEventListener('wxshow', (query) => {
        // TODO 小程序获取供应商店铺id 获取供应商店铺数据
        this.id = this.$route.query.id ? this.$route.query.id : query.id
        // console.log('***supplier-id', this.$route.query)
        // small.wxCache('supidBar', this.id)
        // this.getSupplierFun()
        if (!small.checkLogin()) {
          this.$refs.smalllogin.openSmallLoginPop()
        }
      })

    // 显示顶部导航时
    window.addEventListener('scroll', this.handleScroll, false) // 监听（绑定）滚轮滚动事件
    setTimeout(() => {
      // document.documentElement.scrollTop = 0
      window.scrollTo(0, 0)
    }, 300)
  },
  destroyed() {
    window.removeEventListener('scroll', this.handleScroll, false) // 移除监听
  },
})
</script>

<style lang="scss">
.supplier-home {
  padding-bottom: 100px;
  .default-sup{
    min-height:600px;
    background:url(https://img.wifenxiao.com/h5-wfx/images/supplier/supplier_bg.png) no-repeat;
    background-size: 100% auto;
    .supplier{
      padding:0 20px;
      .supplier-head-top{
        display:flex;
        align-items:center;
        padding:36px 0;
      }
      .shop-logo {
        width: 82px;
        height: 82px;
        margin-right:20px;
        border-radius: 50%;
        border:4px solid #fff;
        box-sizing: content-box;
        img {
          display:block;
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
      }
      .shop-title{
        flex:1;
        font-size: 34px;
        font-weight: bold;
        color: #FFFFFF;
      }
      .btn-member{
        a{
          display:block;
          width:150px;
          height:56px;
          font-size: 28px;
          text-align:center;
          line-height:56px;
          color:#fff;
          background: #F30C23;
          border-radius: 28px;
        }
      }
    }
    .supplier-headerbot-ri {
      ul{
        li {
          position:relative;
          float:left;
          margin-left:150px;
          padding-bottom:16px;
          &:first-child{
            margin-left:0;
          }
          a{
            font-size: 30px;
            // font-weight: 500;
            color: #FFFFFF;
            opacity: 0.8;
          }
          &.active{
            a{
              font-size: 34px;
              font-weight: bold;
              color: #FFFFFF;
              opacity: 1;
            }
            &::after{
              content:"";
              position:absolute;
              bottom:0;
              left:50%;
              width:32px;
              height:10px;
              background:url(https://img.wifenxiao.com/h5-wfx/images/supplier/icon_active.png) no-repeat;
              background-size: 100% 100%;
              transform:translateX(-50%)

            }
          }
        }
      }
    }
    .duodian-mlist-nav{
      &.default{
        padding-top:10px;
        .sort-search-item{
          font-size: 28px;
          line-height:46px;
          color:#fff;
          .sort-icon{
            vertical-align: 2px;
            .icon{
              background-image: url(https://img.wifenxiao.com/h5-wfx/images/public/sort_up_white.png);
              &.up{
                &.selected{
                  background-image:url(https://img.wifenxiao.com/h5-wfx/images/public/sort_up2.png);
                }
              }
              &.down{
                background-image:url(https://img.wifenxiao.com/h5-wfx/images/public/sort_down_white.png);
                &.selected{
                  background-image:url(https://img.wifenxiao.com/h5-wfx/images/public/sort_down2.png);
                }
              }
            }
          }
          .type-txt{
            &.style{
              vertical-align: 4px;
              background-image: url(https://img.wifenxiao.com/h5-wfx/images/item/list/style3.png);
            }
            &#style2{
              background-image: url(https://img.wifenxiao.com/h5-wfx/images/item/list/style4.png);
            }
          }
          &.active{
            color:#F30C23;
            .sort-icon{
              vertical-align: 2px;
              .icon{
                background-image: url(https://img.wifenxiao.com/h5-wfx/images/public/sort_up.png);
                &.up{
                  &.selected{
                    background-image:url(https://img.wifenxiao.com/h5-wfx/images/public/sort_up2.png);
                  }
                }
                &.down{
                  background-image:url(https://img.wifenxiao.com/h5-wfx/images/public/sort_down.png);
                  &.selected{
                    background-image:url(https://img.wifenxiao.com/h5-wfx/images/public/sort_down2.png);
                  }
                }
              }
            }
            .type-txt{
              width:auto;
              padding:0 26px;
              background:#fff;
              border-radius:46px;
            }
          }
        }
      }
      &.fixed{
        position:fixed;
        top:0;
        left:0;
        z-index: 2;
        width:100%;
        border-bottom: 20px solid #f7f7f7;
        background: #fff;
      }
    }
    .newlist{
      .style1{
        overflow:hidden;
      }
    }
  }
  .icon-tel {
    width: 60px;
    height: 60px;
    background: url(https://img.wifenxiao.com/h5-wfx/images/shop/index/tel.png) no-repeat center/cover;
    position: fixed;
    bottom: 15%;
    right: 10%;
  }
  .supplier-tel {
    padding: 40px 0;
    text-align: center;
    font-size: 30px;
    .copy {
      font-size: 20px;
      margin-left: 20px;
      color: #62cef8;
    }
  }
}
</style>
